import { BaseReactElementState, BaseReactElement, reactControl, BaseReactElementControl } from "pao-aop-client";

import React from "react";

import { addon, Ref, getObject, log } from "pao-aop";
import { SignDetailLayout } from "src/projects/industryInternetSign/layout/sgin-detail-layout";
import { ProductSignCondition } from "src/models/singleProductSign";
import SignFrameLayout, { InputType } from "src/business/style-components/sign-frame-layout";
import { NTOperationTable } from "src/business/components/operation-table";
import { ICategoryTemplateSingService, CategorySign } from "src/models/categorySign";
import { match } from "react-router";
import { SIGN_ID, ROUTE_PATH, change_structure, isPermission } from "../../app/util-tool";
import { ColumnConfig } from "src/business/components/detail";
import { IProductTypeService } from "src/models/productType";
import { message } from "antd";
import { PermissionList } from "../../app/permission";

/**
 * 组件：品类标识详情页视图控件状态
 */
export interface CategoryDetailDetailState extends BaseReactElementState {
    /** 单品标识数据源 */
    data?: CategorySign | any;
    /** 品类标识列表数据源 */
    data_source?: any[];
    /** 当前第几页 */
    page?: number;
    /** 当前每页数 */
    pageSize?: number;
    /** 数据总条数 */
    total_data?: number;
    /** 查询条件对象 */
    condition?: ProductSignCondition;
    /** 产品类型列表 */
    product_data?: any;
    /** 滚动条 */
    loading?: boolean;
}

/**
 * 组件：品类标识详情页视图控件
 * 描述
 */
export class CategoryDetailDetail extends BaseReactElement<CategoryDetailDetailViewControl, CategoryDetailDetailState> {

    columns_data_source = [{
        title: '单品名称',
        dataIndex: 'handle_name',
        key: 'handle_name',
        width: 500,
    }, {
        title: '产品类型',
        dataIndex: 'product_type',
        key: 'product_type',
        width: 150,
        render: (text: string, record: any, index: any) => {
            let product = this.state.product_data;
            if (text && product) {
                return product.get(text) ? product.get(text) : text;
            }
        }
    }, {
        title: '单品标识',
        dataIndex: 'handle_code',
        key: 'handle_code',
        width: 500,
    }, {
        title: '创建时间',
        dataIndex: 'create_date',
        key: 'create_date',
        width: 150,
    }];
    constructor(props: CategoryDetailDetailViewControl) {
        super(props);
        this.state = {
            page: 1,
            pageSize: 10,
            loading: false,
            data: {}
        };
    }

    componentWillMount() {
    }

    componentDidMount() {
        this.setState({
            loading: true
        });
        this.queryData()
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("CategoryDetailDetailViewControl", error.message);
            });
    }

    /** 初始化服务 */
    categoryService?() {
        return getObject(this.props.categoryService_Fac!);
    }

    // 初始化产品类型服务
    productTypeService?() {
        return getObject(this.props.productTypeService_Fac!);
    }

    /** 分页回调事件 */
    pageOnCick = (contents: any) => {
        console.log('page:', contents);
        this.setState({
            page: contents,
            loading: true
        });
        this.queryList(this.state.condition ? this.state.condition! : {}, contents, this.state.pageSize!)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("CategoryTemplateDetailViewControl", error.message);
            });
    }

    /** 改变分页数量回调事件 */
    showSizeChange = (current: number, pageSize: number) => {
        console.log('current: ' + current + 'pageSize: ' + pageSize);
        this.setState({
            pageSize: pageSize,
            loading: true
        });
        this.queryList(this.state.condition ? this.state.condition! : {}, 1, pageSize)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("CategoryTemplateDetailViewControl", error.message);
            });
    }

    /** 修改Icon回调事件 */
    onClickEditor = () => {
        this.props.history!.push(ROUTE_PATH.changeCategoryTemplate + `/${this.state.data!.id}`);
    }

    /** 删除Icon回调事件 */
    onClickDel = () => {
        this.setState({
            loading: true
        });
        this.deleteDeatail()
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("CategoryDetailDetailViewControl-delete", error.message);
            });
        this.props.history!.push(ROUTE_PATH.categoryTemplate);
    }

    /** 查询回调 */
    private searchCategory = (e: any, val: any) => {
        this.setState({
            condition: val,
            loading: true
        });
        this.queryList(val, 1, this.state.pageSize ? this.state.pageSize : 10)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("CategoryDetailDetailViewControl", error.message);
            });
    }

    /** 重置回调 */
    private reset = () => {
        console.log("重置回调");
        this.setState({
            condition: {}
        });
    }

    /** 获取单品列表信息 */
    async queryList(condition: ProductSignCondition, page: number, count: number) {
        condition.id = this.state.data!.id;
        const data_list = await this.categoryService!()!.get_single_list!(condition, page, count)!;
        this.setState(
            {
                data_source: data_list ?
                    data_list!['result']
                    :
                    []
            }
        );
    }

    /** 删除品类详情信息 */
    async deleteDeatail() {
        let { [SIGN_ID]: id } = this.props.match!.params;

        const result = await this.categoryService!()!.delete_category!([id])!;
        message.info("删除" + result ? '成功' : '失败');
    }

    /** 查询详情信息 */
    async queryData() {
        let { [SIGN_ID]: id } = this.props.match!.params;
        let condition: ProductSignCondition = { id: id };
        const data = await this.categoryService!()!.get_category!(id)!;
        const data_list = await this.categoryService!()!.get_single_list!(condition, this.state.page ? this.state.page : 1, this.state.pageSize ? this.state.pageSize : 10)!;
        const product_data = await this.productTypeService!()!.get_product_type_list!()!;
        let product_map = change_structure('product_type_name', product_data!.result);
        /** 把产品类型转成中文 */
        if (data && data.product_type) {
            let key = data.product_type;
            data.product_type = product_map.get(key) ? product_map.get(key) : key;
        }
        this.setState({
            condition: condition,
            data: data,
            total_data: data_list ? data_list!.total : 0,
            data_source: data_list ? data_list!.result : [],
            product_data: product_map
        });
    }
    render() {
        const redeirect = isPermission ? isPermission!(PermissionList.SingleProduct_Select) : undefined;
        if (redeirect) {
            return redeirect;
        }
        let title_detail_columns: ColumnConfig[] = [
            { title: '品类模板标识:', fieldName: 'handle_code' },
            { title: '产品类型:', fieldName: 'product_type' },
            { title: '创建日期:', fieldName: 'create_date' },
        ];
        let { data, data_source } = this.state;

        if (data && data.custom_attribute) {
            for (let i = 0; i < data.custom_attribute.length; i++) {
                title_detail_columns.push({
                    title: data.custom_attribute[i].label! + ':', // + (data.custom_attribute[i].value instanceof Array ? '' : data.custom_attribute[i].value!),
                    fieldName: 'custom_attribute' + i, // data.custom_attribute[i].value!,
                    type: data.custom_attribute[i].value instanceof Array ? 'img' : undefined
                });
                data['custom_attribute' + i] = data.custom_attribute[i].value!;
            }
        }

        let category_model_props = {
            edit_form_items_props: [{
                type: InputType.input,
                label: "单品名称",
                decorator_id: "handle_name",
                default_value: "",
                option: {
                    placeholder: "请输入单品名称"
                }
            },
            {
                type: InputType.input,
                label: "标识码",
                decorator_id: "handle_code",
                default_value: "",
                option: {
                    placeholder: "请输入标识码"
                }
            },
            {
                type: InputType.date,
                label: "创建时间",
                decorator_id: "create_date",
                default_value: ""
            }],

            showTable: (
                <NTOperationTable
                    data_source={data_source}
                    columns_data_source={this.columns_data_source}
                    table_size='middle'
                    showHeader={true}
                    bordered={false}
                    total={this.state.total_data ? this.state.total_data : 0}
                    default_page_size={10}
                    total_pages={Math.ceil((this.state.total_data ? this.state.total_data : 1) / 10)}
                    show_footer={true}
                    page_on_click={this.pageOnCick}
                    show_size_change={this.showSizeChange}
                    rowKey='id'
                />),
            search_cb: this.searchCategory,
            reset_cb: this.reset
        };

        let this_props = {
            loading: this.state.loading,
            title_name: data!.handle_name,
            rc_code: data!.rc_code,
            title_detail_columns: title_detail_columns,
            title_detail_columns_data: data,
            icon_props: [{
                icon: 'antd@edit',
                btn_method: this.onClickEditor
            }, {
                icon: 'antd@delete',
                btn_method: this.onClickDel
            }],
            picture: { title_name: '品类模板图片', picture_data: data!.category_picture },
            tab: [{
                name: '引用该模板的单品标识',
                showElement: (
                    <SignFrameLayout {...category_model_props} />
                )
            }]
        };
        return (
            <SignDetailLayout {...this_props} />
        );
    }
}

/**
 * 控件：品类标识详情页视图控件
 * 控制品类标识详情页视图控件
 */
@addon('CategoryDetailDetail', '品类标识详情页视图控件', '控制品类标识详情页视图控件')
@reactControl(CategoryDetailDetail, true)
export class CategoryDetailDetailViewControl extends BaseReactElementControl {
    /**
     * 单品标识服务
     */
    public categoryService_Fac?: Ref<ICategoryTemplateSingService>;
    /** 
     * 产品类型服务
     */
    public productTypeService_Fac?: Ref<IProductTypeService>;

    match?: match<{ [SIGN_ID]: string }>;
}